
import { store } from '@/store';

// 1.1 create user relation store
import { defineStore } from 'pinia';

// 2.1 import dataType
import type { GetUserInfoModel, LoginParams } from '@/api/sys/model/userModel';


// 2.2 import request iface fun
import { getUserInfo, loginApi } from '@/api/sys/user';

// 2.3 import tokenKit
import { TokenKit } from '@/utils/auth/token';

// 2.4 import router for combine router by server

// 2.5 import userState
import type { UserState } from '@/store/types/types';

// 1.2 define store
export const useUserStore = defineStore(
    'app-user', {
         // 2.1 状态机处理  UserState  用于控制 数据状态 类型
        state: (): UserState => ({
            // user info
            // userInfo: null,
            // token
            token: TokenKit.GET_TOKEN(),
            rolename : '',
            isSetUser: false,
            // roleList
            roleList: [],
            // Whether the login expired
            sessionTimeout: false,
            // Last fetch time
            lastUpdateTime: 0,
    }),
       // 2.2 异步/逻辑处理
    actions: {
      async userLogin(params: LoginParams) {
        // console.log(console.log(data));
        // let result:LoginResponse = await reqLogin(data);
          const data = await loginApi(params)
          if (data&&data.token) {
              TokenKit.SET_TOKEN(data.token as string);
              this.token = TokenKit.GET_TOKEN();
              return 'ok'
          } 
          return 'error';
      },
  
      async userInfo() {
        // 1.1 acqure user info (avatar,username)
        const result: GetUserInfoModel = await getUserInfo();
        // console.log(result);
        // 1.2 save userInfo
        this.isSetUser = true
        this.username = result&&result.userName;
        this.roleList = result&&result.roleListName;
        // this.avatar = result.avatar;
        return 'ok'
      },
  
      loginOut() {
        // 1.1 clear token
        TokenKit.REMOVE_TOKEN()
        // 1.2 clear user info
        this.token = '';
        this.isSetUser = false
        this.username = '';
        this.avatar = ''
      },
   

    // ,
    // setUser(user) {
    //     this.user = user;
    // }
  },
  getters: {
    getIsSetUser(): boolean {
      return this.isSetUser
    },

    getRoleName(): string {
      return this.roleList
    }

  },
})

// 1.3 export store
export default useUserStore


export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
